package com.lance.answer.gui.answer;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lance.answer.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WatchVideo1010 {

    //http://www.nmg.gov.cn/mas/openapi/pages.do?method=exPlay&appKey=gov&id=5716&autoPlay=false
    //https://vod.300hu.com/4c1f7a6atransbjngwcloud1oss/5d82e52a382171174942019585/v.f30.mp4
    //http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4
    //https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4
    public static final String JS = "var video = document.getElementsByTagName(\"video\");if(video.length>0){ video[0].src = \"https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4\";}";

    public static void main(String[] args) throws Exception {
        //课程名
        String subjectName = "毛泽东思想和中国特色社会主义理论体系概论";
     //   String subjectName = "形势与政策";
        //  String subjectName = "马克思主义基本原理概论";
        //专业名
        //   String majorName = "工商企业管理";
        // String majorName = "法律事务";
        //   String majorName = "小学教育";
        //     String majorName = "工程造价";  //FIXME 工程造价是马克思主义！！！！！！！！
        //  String majorName = "计算机信息管理";
        //     String majorName = "all1";
        //  String majorName = "行政管理专科2103"; //DONE
        //    String majorName = "建设工程管理专科2013秋"; // DONE
        // String majorName = "other"; //135 134完成，还有一位未知
     //   String majorName = "other1";
      //  String majorName = "小学教育专科2103";
      //  String majorName = "行政管理专科2103";
        String majorName = "alltmp";
   //     String majorName = "法律事务（新疆试点方向）专科2103";
        // FIXME 会计学 马克思主义基本原理概论
        // all: 人力资源管理 机电一体化 水利水电工程管理 汉语言文学 计算机网络技术 金融管理
        // all2: 工程造价 会计学
        //并发度
        int sync = 11;
        //是否开启休眠-兼容服务器停服
        boolean open = false;

        run(subjectName.trim(), majorName.trim(), sync, open);
    }

    public static void run(String subjectName, String majorName, int sync, boolean open) throws Exception {
        //初始化日志
        Constant.initLog();
        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-video.section");
        List<String> paths = IOUtils.readLines(inputStream3);

        InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + "users/" + majorName + ".user");
        List<String> users = IOUtils.readLines(inputStream2, "utf-8");

        log.info("本次刷视频 课程名称：{},专业名称：{}", subjectName, majorName);
        log.info("本次加载用户：{} 人", users.size());

        List<List<String>> group = new ArrayList<>();
        int size = users.size();
        int step = size / sync;
        if (step == 0) {
            group.add(users);
        } else {
            for (int i = 0; i < sync; i++) {
                List<String> list2 = users.subList(step * i, (i + 1) * step);
                group.add(list2);
            }
            group.add(users.subList(step * sync, users.size()));
        }

        log.info("本次程序将加载 {} 个线程同时运行", group.size());
        for (List<String> batchUser : group) {
            Constant.THREAD_POOL_BATCH.execute(() -> {
                try {
                    int i = 1;
                    log.info("线程：{} 将执行 {} 个用户视频观看任务", Thread.currentThread().getName(), batchUser.size());
                    for (String user : batchUser) {
                        String[] strs = user.split(",");
                        String userCode = strs[0];
                        String pwd;
                        if (strs[1].length() == 8) {
                            pwd = strs[1];
                        } else {
                            pwd = strs[1].substring(6, 14);
                            pwd = "Ouchn" + pwd;
                        }

                        long start = System.currentTimeMillis();
                        log.info("线程：{} 开始执行第：{} 个用户视频观看任务，用户名：{}", Thread.currentThread().getName(), i, userCode);
                        //   run(paths,subjectName,"d:\\ynouAutoStudy\\chromedriver.exe",userCode,pwd,open);
                        run(paths, subjectName, null, userCode, pwd, open);

                        long end = System.currentTimeMillis();
                        log.info("线程：{} 第：{} 个用户视频观看任务结束,耗时：{} min,用户名：{}", Thread.currentThread().getName(), i, (end - start) / 1000 / 60, userCode);
                        log.info("线程：{} 当前用户进度：{} / {}", Thread.currentThread().getName(), i, batchUser.size());
                        i++;
                    }
                    log.info("线程：{} 任务执行完毕", Thread.currentThread().getName());


                } catch (Exception e) {
                    e.printStackTrace();

                }

            });

        }

    }

    public static void run(List<String> urlTasks,String subjectName,String driverPath,String userName,String password,boolean open) throws Exception {
        ChromeDriver driver = Util.getDriver(driverPath);
        try{
            String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
            driver.get(url);
            Thread.sleep(6000);
            Util.login(driver, userName, password);
            //Util.switchToLast(driver);
            Thread.sleep(6000);
            // 形考作业的链接 管理学

            boolean isFind = false;
            for (WebElement we : driver.findElements(By.className("media-body"))) {
                String mediaTitle = we.findElement(By.className("media-title")).getText();

                if (!mediaTitle.contains(subjectName)) {
                    continue;
                }
                //点击进入学习的按钮
                WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                studyButton.click();
                isFind = true;
                //Util.switchToLast(driver);
                Thread.sleep(6000);
            }

            if(!isFind){
                return;
            }

            // TODO 在这里统计有多少个视频已经刷了
            Util.switchToLast(driver);

            int index = 1;
            //sectionname
            for(WebElement h3:driver.findElements(By.cssSelector("h3[class='sectionname']"))){

                String h3Text = h3.getText();
                if(Strings.isNullOrEmpty(h3Text)){
                    continue;
                }
                if(h3Text.contains("专题一")){
                    continue;
                }
                if (index > 4) {
                    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,100000)");
                }
           //     System.err.println("index:"+index);
                if(h3Text.contains("专题")){
                    index++;
                    Thread.sleep(4000);
                    h3.click();
                }
            }

            Thread.sleep(4000);
           // System.err.println("findElements:"+driver.findElements(By.cssSelector("div[class='mod-indent-outer w-100']")).size());
       //     System.err.println("findElements2:"+driver.findElements(By.cssSelector("li[class='activity url modtype_url ']")).size());

            List<String > completeUrlList = Lists.newArrayList();
      //      for(WebElement activityinstance:driver.findElements(By.cssSelector("div[class='activityinstance']"))){
         //   for(WebElement activityinstance:driver.findElements(By.cssSelector("div[class^='mod-indent-outer w-100']"))){

            List<WebElement> activityinstanceList = driver.findElements(By.cssSelector("li[class^='activity url modtype_url']"));
            if(activityinstanceList == null||activityinstanceList.size()==0){
                return;
            }
            for(WebElement activityinstance:activityinstanceList){
                String instanceText = activityinstance.getText();
                if(Strings.isNullOrEmpty(instanceText)){
                    continue;
                }
                if(!instanceText.contains("视频")){
                    continue;
                }
           //     System.err.println("instanceText:"+instanceText);

                try {

                    // FIXME 有两种判断方法
                    WebElement btnWe =   Util.findByCssSelector(activityinstance,"button[class='btn btn-link'],span[class='autocompletion']");
                    if(btnWe== null){
                        continue;
                    }
                    WebElement imgWe = Util.findByCssSelector(btnWe,"img[class^='icon']");
                    if(imgWe== null){
                        continue;
                    }
                    String imgText = imgWe.getAttribute("title");
              //      System.err.println("imgText:"+imgText);
                    if(Strings.isNullOrEmpty(imgText)){
                        continue;
                    }
                    if(imgText.contains("已完成")){
                        completeUrlList.add(activityinstance.findElement(By.cssSelector("a[class='aalink']")).getAttribute("href"));
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            Thread.sleep(2000);

            //System.out.println(urlTasks.toString());
            log.info("线程：{} 用户: {} 需观看 {} 个视频",Thread.currentThread().getName(),userName,urlTasks.size());
            int j = 1;
            for (String urlTask : urlTasks) {
                //兼容服务器停服问题
                if (open) {
                    while (LocalDateTime.now().getHour() >= 3 && LocalDateTime.now().getHour() < 5 ) {
                        log.info("当前时间：{} 国开网维护中 程序暂时休眠20min。。。",LocalDateTime.now().toString());
                        TimeUnit.MINUTES.sleep(20);
                    }
                }

                if(completeUrlList.contains(urlTask)){

                //    System.err.println("urlTask:::"+urlTask);
                    continue;
                }

                // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
                driver.get(urlTask);

                //延长加载时间
                Thread.sleep(5 * 1000);
                // Util.switchToUrl(driver,urlTask);
                Util.switchToLast(driver);
                log.info("线程：{} 用户：{} 当前视频观看进度（{} / {})",Thread.currentThread().getName(),userName,j,urlTasks.size());
                Thread.sleep(2 * 1000);
                driver.executeScript(JS);
                Thread.sleep(2 * 1000);
                List<WebElement> canvas = driver.findElements(By.tagName("canvas"));
                //System.out.println("canvas大小");
                //System.out.println(canvas.size());
                for (WebElement player:canvas) {
                    //System.out.println("class是：" + player.getAttribute("class"));
                    if (player.getAttribute("class").startsWith("play")) {
                        //System.out.println("找到啦 ");
                        //System.out.println(player);
                        player.click();
                    }else {
                        continue;
                    }
                }

                Thread.sleep(18000);
                j++;
            }
        }catch (Exception e){
            e.printStackTrace();
            Thread.sleep(2000);
        }finally {
          try{
              driver.close();
              driver.quit();
          }catch (Exception e){

          }
        }
    }

}
